/* eslint-disable no-lonely-if */
/* eslint-disable no-restricted-globals */
import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'dva';

import { Button, DatePicker, Select } from 'antd';
import ProTable from '@ant-design/pro-table';
import { useDebounceFn } from '@umijs/hooks';
import { PageContainer } from '@ant-design/pro-layout';
import { manage, fetchObject } from '@/pages/scale/service/compose';
import AutoComplete from '@/components/AutoComplete';

// import ScaleTypeDropDown from '@/pages/scale/components/type/ScaleTypeDropDown';
import ScaleReportModal from '@/components/Scale/ScaleReportModal';

import router from '@/utils/router';
import moment from 'moment';

const { RangePicker } = DatePicker;

/**
 * actionRef={actionRef} 加上這一行影響的
 */

const AssessmentRecord = ({
  patriarchAssessmentRecord,
  dispatch,
  header = true,
  code,
  print = false,
}) => {
  const { scales = [], records } = patriarchAssessmentRecord;

  // objects
  const fromRef = useRef();
  // const actionRef = useRef();
  // const ref = useRef<FormInstance>();

  const [report, setReport] = useState();
  const [objects, setObjects] = useState([]);
  const [object, setObject] = useState();

  const loadObjects = async (number) => {
    const res = await fetchObject({ text: number });
    setObjects(res.content);
  };

  /**
   * 避免短時間內重複查詢
   */
  const { run: handleSearch } = useDebounceFn((number) => {
    loadObjects(number);
  }, 500);

  const getScaleSelect = () => {
    return (
      <Select placeholder="量表类型">
        {scales
          ? scales.map((item) => (
              <Select.Option value={item.id} key={item.id}>
                {item.name}
              </Select.Option>
            ))
          : ''}
      </Select>
    );
  };

  const columns = [
    {
      title: '答题时间',
      dataIndex: 'reportDate',
      render: (value) => {
        if (isNaN(value) === false) {
          return moment(value).format('YYYY-MM-DD');
        }
        return '';
      },
      renderFormItem: () => {
        return <RangePicker placeholder={['开始日期', '结束日期']} />;
      },
    },
    {
      title: '姓名',
      dataIndex: 'userName',
      search: false,
    },
    {
      title: '报告编号',
      dataIndex: 'number',
      search: false,
    },
    {
      title: '量表类型',
      dataIndex: 'scaleName',
      renderFormItem: () => {
        return getScaleSelect();
      },
    },
    {
      title: '人员代码',
      dataIndex: 'user',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <AutoComplete
            allowClear
            label="人员代码"
            onInputChange={(value) => {
              const vs = value.split('.');
              if (vs.length === 1) {
                handleSearch(value);
              }
            }}
            onEmpty={() => {
              setObject(null);
            }}
            onChange={({ value }) => {
              setObject(value);
            }}
            options={objects.map((i) => {
              return {
                value: i.id,
                label: `${i.number}.${i.name}`,
              };
            })}
          />
        );
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Button
          size="small"
          type="success"
          onClick={() => {
            if (record.reportDate) {
              setReport({ scale: record.scale, id: record.id });
            } else {
              if (record.subScale) {
                router.push(
                  `/scale/compose/answer/single?compose=${record.scale}&id=${record.id}&subScale=${record.subScale}`,
                );
              } else {
                router.push({
                  pathname: '/scale/compose/answer',
                  query: { compose: record.scale, id: record.id, name: record.scaleName },
                });
              }
            }
          }}
        >
          {record.reportDate ? '查看量表结果' : '继续答题'}
        </Button>
      ),
    },
  ];
  if (print) {
    columns.splice(-1);
  }

  useEffect(() => {
    dispatch({
      type: 'patriarchAssessmentRecord/fetchScaleData',
    });
    return () => {
      dispatch({
        type: 'patriarchAssessmentRecord/clear',
        payload: {},
      });
    };
  }, []);

  return (
    <>
      {header && (
        <PageContainer>
          <ProTable
            // formRef={fromRef}
            rowKey="id"
            search={{
              labelWidth: 80,
            }}
            columns={columns}
            // onSubmit={search}
            request={async (params, sort, filter) => {
              const { scaleName, reportDate, current, pageSize } = params;
              const res = await manage({
                values: {
                  user: object || '',
                  scale: scaleName || '',
                  start: reportDate ? reportDate[0] : '',
                  end: reportDate ? reportDate[1] : '',
                },
                pagination: { page: current, size: pageSize },
              });
              return {
                data: res.content,
                success: true,
                total: res.totalElements,
              };
            }}
          />
          <ScaleReportModal
            report={report}
            onClose={() => {
              setReport();
            }}
          />
        </PageContainer>
      )}
      {!header && (
        <>
          <ProTable
            style={{ width: '100%' }}
            rowKey="id"
            search={
              print
                ? false
                : {
                    labelWidth: 80,
                  }
            }
            toolBarRender={!print}
            pagination={!print}
            columns={columns}
            // onSubmit={search}
            params={{ code }}
            request={async (params, sort, filter) => {
              const { scaleName, reportDate, current, pageSize } = params;

              const res = await manage({
                values: {
                  scale: scaleName || '',
                  start: reportDate ? reportDate[0] : '',
                  end: reportDate ? reportDate[1] : '',
                },
                // 打印时不需要分页，则默认传1和20
                pagination: { page: current || 1, size: pageSize || 20 },
              });
              const data = res.content.filter((item) => item.userNumber === code);
              return {
                data,
                success: true,
                total: res.totalElements,
              };
            }}
          />
          <ScaleReportModal
            report={report}
            onClose={() => {
              setReport();
            }}
          />
        </>
      )}
    </>
  );
};
export default connect(({ patriarchAssessmentRecord, loading }) => ({
  loading: loading.effects['patriarchAssessmentRecord/listType'],
  patriarchAssessmentRecord,
}))(AssessmentRecord);
